package com.eastcom.collection.script

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress.Cache;
import java.sql.Date;
import java.sql.PreparedStatement
import java.sql.SQLException
import java.sql.Timestamp
import java.sql.Types;
import java.text.SimpleDateFormat
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.eastcom.collection.tools.common.JmsJndiConfig
import com.eastcom.collection.tools.common.MQCommunication
import com.eastcom.collection.tools.common.ShellExecutor;
import com.eastcom.collection.tools.db.DbEngine
import com.eastcom.collection.tools.file.FileUtils;
import com.eastcom.collection.tools.file.FtpUtils;
import com.eastcom.collection.config.FtpTaskConfig
import com.eastcom.collection.provider.*
import com.eastcom.collection.tools.mail.*
import com.sun.java.util.jar.pack.Instruction.Switch;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.bcel.internal.util.ClassPath.Dir;
import com.eastcom.collection.tools.db.DbEngine
import com.eastcom.collection.tools.file.JaxbUtil;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPFile
import org.apache.commons.net.ftp.FTPFileFilter
import org.apache.tools.ant.types.FileList;
import org.springframework.dao.DataAccessException
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback
import org.springframework.jdbc.support.lob.LobCreator
import org.springframework.jdbc.support.lob.OracleLobHandler
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
 * 任务类，可配置
 * @author yuanyue
 *
 */
class SimpleFtpDownloadTaskDirector {
	/************************配置属性，可以修改，请尽量使用英文防止中文编码问题***************************/
	String localRootPath
	final String ftpInfoRegex = "([0-9]+\\.\\d+\\.\\d+\\.\\d+):(\\d+)"
	List<String> ftpRemotePath = new ArrayList()
	List<String> ftpLocalPath = new ArrayList()
	List<List<String>> ftpFileNameRegex = new ArrayList()
	//没有时间的话用[]
	List<List<String>> fileNameTimeFormat = new ArrayList()
	String ftpIp
	String ftpUser
	String ftpPasswd
	int ftpPort = 21
	int ftpFileLimit = 200
	String ftpSystem = "UNIX"
	String ftpControlEnCode = "UTF-8"
	String ftpFileEnCode = "UTF-8"
	String ftpServerLanguage = "zh"
	long fileLimit = 20000000000
	/***************************可配置部分结束***********************************************/

















	static ThreadPoolTaskExecutor threadPoolTaskExecutor
	static Log logger = LogFactory.getLog(SimpleFtpDownloadTaskDirector.class)



	/*********************initJob和doJob是要被程序调用的方法**************************/
	public boolean initJob(String jobId){

	}

	public boolean doJob(String jobId){
		ConcurrentLinkedQueue ftpTaskWorkQueue = SpringContextProvider.getBean("ftpTaskWorkQueue")
		ConcurrentLinkedQueue parseTaskWorkQueue = SpringContextProvider.getBean("parseTaskWorkQueue")
		if(ftpTaskWorkQueue.isEmpty()){
			return true
		}
		FtpTaskConfig ftpTaskCf = ftpTaskWorkQueue.poll()
		String taskString = JaxbUtil.convertToXmlString(ftpTaskCf)
		String ConnectionString = ftpTaskCf.ConnectionString
		Pattern pattern = Pattern.compile(ftpInfoRegex)
		Matcher mat = pattern.matcher(ConnectionString);
		boolean rs = mat.find()
		String ip
		String port
		if(rs){
			ip = mat.group(1)
			port = mat.group(2)
		}else{
			logger.error("ftp 信息不正确！taskinfo=["+taskString+"]")
			return false
		}
		this.ftpIp = ip
		this.ftpPort = Integer.valueOf(port)
		this.ftpUser = ftpTaskCf.userName
		this.ftpPasswd = ftpTaskCf.password
		this.ftpRemotePath.add(ftpTaskCf.Path)
		this.localRootPath = PropertyPlaceholderConfigurerProvider.getContextProperty("LOCAL_ROOT_PATH")
		String lp = localRootPath
		if(! ftpTaskCf.Path.startsWith("/")&&!ftpTaskCf.Path.startsWith("\\")){
			lp += "/"
		}
		lp += ftpTaskCf.Path
		ftpTaskCf.localPath = lp
		this.ftpLocalPath.add(lp)
		String[] fileName = ftpTaskCf.FileList.split("\\s*;\\s*")
		List<String> fileNameList = new ArrayList<String>()
		fileName.each {
			fileNameList.add(it)
		}
		ftpTaskCf.fileNameList = fileNameList
		this.ftpFileNameRegex.add(fileNameList)
		this.ftpFileEnCode = ftpTaskCf.files.file.get(0).CharSet
		ftpTaskCf.encode = ftpTaskCf.files.file.get(0).CharSet
		doFtp(ftpRemotePath,ftpLocalPath,ftpFileNameRegex)
		parseTaskWorkQueue.add(ftpTaskCf)
	}

	private boolean doFtp(List<String> ftpRemotePath,List<String> ftpLocalPath,List<List<String>> ftpFileNameRegex){
		try{
			FTPFile[] acceptFiles = null;
			FtpUtils ftpUtils = new FtpUtils();
			ftpUtils.login(ftpIp, ftpPort, ftpUser, ftpPasswd, ftpSystem, ftpControlEnCode, ftpServerLanguage);
			for(int i = 0; i < ftpRemotePath.size(); i++){
				String rp = ftpRemotePath[i]
				String lp = ftpLocalPath[i]
				File dirFile = new File(lp);
				if(! dirFile.exists()){
					dirFile.mkdirs();
				}
				ftpUtils.getFtp().changeWorkingDirectory(rp);
				List<String> fileNameRegex = ftpFileNameRegex[i]
				for(int j = 0; j < fileNameRegex.size(); j++){
					String nameRegex = fileNameRegex[j]
					Pattern pat = Pattern.compile(nameRegex);
					acceptFiles = ftpUtils.getFtp().listFiles(null, new FTPFileFilter() {
								private int fileCount = 0;
								@Override
								public boolean accept(FTPFile file) {
									// TODO 自动生成的方法存根
									String name = file.getName();
									Matcher mat = pat.matcher(name);
									boolean rs = mat.find();
									if(! rs){
										return false
									}
									File localFile = new File(lp);
									String[] localFiles = localFile.list();
									if(localFiles != null){
										for(String lf: localFiles){
											if(lf.equalsIgnoreCase(name)){
												return false;
											}
										}
									}

									if(fileCount > ftpFileLimit){
										return false;
									}
									fileCount++;
									return true;
								}
							});
					boolean res = false;
					int count = 0;
					logger.debug("接收的文件数量："+acceptFiles.length);
					for(int k = 0; k < acceptFiles.length; k++){
						String fileName = acceptFiles[k].getName();
						File f = null;
						String dir = lp

						if(dir.endsWith("/")||dir.endsWith("\\")||dir.endsWith("\\\\")){
							f=new File(dir+fileName);
						}else{
							f=new File(dir+"/"+fileName);
						}
						OutputStream os=new FileOutputStream(f);
						res = ftpUtils.getFtp().retrieveFile(fileName, os);
						if(res){
							count ++;
						}
						os.flush()
						os.close()
						logger.debug("下载了"+count+"文件！")

					}
				}

			}
		}catch (Exception e) {
			logger.error(this, e);
		}
	}
}